package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Service
@Slf4j
public class DishServiceImpl implements DishService {


    @Resource
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional(rollbackFor = SQLException.class)
    @Override
    public Integer addDish(DishDTO dishDTO) {
        //1.新增菜品
        //把DTO的数据转实体类对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        log.info("[新增菜品前] dish:{}", dish);
        Integer tag = dishMapper.insertDish(dish);
        Long dishId = dish.getId();
        log.info("[新增菜品完毕] dish:{}", dishId);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.stream().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
                //一个个插入到数据库
                dishFlavorMapper.insertDishFlavor(dishFlavor);
            });
        }
        return tag;
    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult findByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = new PageResult();
        //启用分页查询,传入page和pageSize
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        List<DishVO> dishVOList = dishMapper.selectByPage(dishPageQueryDTO);
        Page<DishVO> dishVOPage = (Page<DishVO>) dishVOList;
        pageResult.setTotal(dishVOPage.getTotal());
        pageResult.setRecords(dishVOPage.getResult());
        return pageResult;

    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = SQLException.class)
    @Override
    public Integer batchDelete(List<Long> ids) {
        //删除菜品
        Integer tag = dishMapper.deleteByIds(ids);
        //删除菜品对应口味
        dishFlavorMapper.deleteByIds(ids);
        return tag;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        return dishMapper.list(dish);

    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        // 先读Redis缓存，如果缓存有，直接返回，如果没有，读数据库，把数据放入redis
        //dish_分类ID
        String key = "dish_" + dish.getCategoryId();
        Object objList = redisTemplate.opsForValue().get(key);
        if (objList != null) {
            log.info("[丛redis读取菜品列表]");
            List<DishVO> dishVOList = (List<DishVO>) objList;
            return dishVOList;
        }
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set(key,dishList);
        log.info("[读取列表],存redis...");
        return dishVOList;
    }

    /**
     * 回显
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findById(Long id) {
        Dish dish = dishMapper.findById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        dishVO.setFlavors(flavors);
        BeanUtils.copyProperties(dish, dishVO);
        return dishVO;
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     * @return
     */
    @Override
    public Integer xiuGaiDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        Integer tage = dishMapper.updataDish(dish);
        dishFlavorMapper.deleteById(dish.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(new Consumer<DishFlavor>() {
                @Override
                public void accept(DishFlavor dishFlavor) {
                    dishFlavor.setDishId((dish.getId()));
                    dishFlavorMapper.insertDishFlavor(dishFlavor);
                }
            });
        }
        return tage;
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public Integer startOrStopDish(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        return dishMapper.updataDish(dish);
    }
}
